package com.lemon.components.wechart.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.lemon.components.wechart.UploadService;
import com.lemon.components.wechart.WechartBase;
import com.lemon.components.wechart.enums.MediaTypeEnum;
import com.lemon.components.wechart.order.media.GetMediaOrder;
import com.lemon.components.wechart.order.media.UploadMediaOrder;
import com.lemon.components.wechart.result.media.GetMediaResourceResult;
import com.lemon.components.wechart.result.media.UploadResult;

public class UploadServiceImpl extends WechartBase implements UploadService {
	private final String MEDIAUPLOADURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%1$s&type=%2$s";
	private final String MEDIAGETURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%1$s&media_id=%2$s";
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public UploadResult upload(UploadMediaOrder uploadOrder) {
		uploadOrder.check();
		UploadResult uploadResult = new UploadResult();
		
		String str = upload(String.format(MEDIAUPLOADURL, uploadOrder.getAccessToken(),uploadOrder.getType().getCode()), 
				uploadOrder.getMedia(),uploadOrder.getInputStream());
		
		JSONObject jsonObject = JSONObject.parseObject(str);
		int errcode = jsonObject.getIntValue("errcode");
		if (errcode > 0) {
			uploadResult.setErrcode(errcode);
			uploadResult.setErrmsg(jsonObject.getString("errmsg"));
			return uploadResult;
		} else {
			uploadResult.setType(MediaTypeEnum.valueOf(jsonObject.getString("type")));
			uploadResult.setMediaId(jsonObject.getString("media_id"));
			uploadResult.setCreatedAt(jsonObject.getLongValue("created_at"));
			return uploadResult;
		}
	}
	
	@Override
	public GetMediaResourceResult getMediaResource(GetMediaOrder getMediaOrder){
		GetMediaResourceResult getMediaResourceResult = new GetMediaResourceResult();
		String url = String.format(MEDIAGETURL, getMediaOrder.getAccessToken(),getMediaOrder.getMediaId());
		String str = getCommand(url);
		try {
			JSONObject jsonObject = JSONObject.parseObject(str);
			int errcode = jsonObject.getIntValue("errcode");
			getMediaResourceResult.setErrcode(errcode);
			getMediaResourceResult.setErrmsg(jsonObject.getString("errmsg"));
			getMediaResourceResult.setVideoUrl(jsonObject.getString("video_url"));
			return getMediaResourceResult;
		} catch (Exception e) {
			logger.warn("Json转换出错",e.getMessage());
		}
		System.out.println(str);
		getMediaResourceResult.setResource(str.getBytes());
		getMediaResourceResult.setUrl(url);
		return getMediaResourceResult;
	}
}
